package com.atguigu.srb.oss.controller.api;

import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author lupengning
 * @version 1.0
 * @description:
 * @date 2021/6/5 3:27
 */
@RestController
@Slf4j
@Api(tags = "文件管理")
//@CrossOrigin
@RequestMapping("/api/oss/file")
public class FileController {

  @Autowired
  private FileService fileService;

  @ApiOperation("上传文件")
  @PostMapping("/upload")
  public R upload(@ApiParam(value = "文件",required = true)
                  @RequestParam(value = "file")
                  MultipartFile file,
                  @ApiParam(value = "模块",required = true)
                  @RequestParam(value = "module")
                  String module) {
    try {
      String url = fileService.upload(file.getInputStream(), module, file.getOriginalFilename());
      return R.ok().message("上传文件成功！").data("url",url);
    } catch (IOException e) {
      throw new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
    }
  }

  /**
   * 删除文件
   * @return
   */
  @ApiOperation("删除Oss文件")
  @DeleteMapping("/remove")
  public R remove(@RequestParam("url") @ApiParam("要删除的文件") String url) {
    fileService.removeFile(url);
    return R.ok().message("删除文件成功！");
  }
}
